<template>
  <main>
    <h1>免费在线 BMI 计算器</h1>
    <BmiForm @my-submit="parentSubmit"/>
    <h2>BMI列表</h2>
    <table border="1">
      <thead>
      <tr>
        <th>#</th>
        <th>日期</th>
        <th>身高</th>
        <th>体重</th>
        <th>BMI</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody v-if="bmi.bmiList.length > 0">
      <BmiItem
          v-for="(item, index) of bmi.bmiList"
          :key="item.id"
          :index="index + 1"
          :item="item"
          @onDel="onDelete"
      />
      </tbody>
      <tbody v-else>
      <tr><td style="text-align: center" colspan="6">暂无数据</td></tr>
      </tbody>
    </table>
  </main>
</template>

<!-- // 选项式的api，最大优势代码自由，不考虑配置项 -->
<script setup>
import BmiForm from "../components/bmi/BmiForm.vue";
import BmiItem from "../components/bmi/BmiItem.vue";
import { ref, onBeforeMount } from 'vue'

import { useBMIStore } from '../stores/bmi'

const bmi = useBMIStore()

const getList = async () => {
  // 优雅
  try {
    await bmi.fetchBMIList()
  } catch (e) {
    console.log(e)
  }
}

onBeforeMount(async () => {
  await getList()
})

const parentSubmit = async (val) => {
  try {
    await bmi.createBMI(val)
    await getList()
  } catch (e) {
    console.log(e)
  }
}

const onDelete = async (id) => {
  if (confirm('确定要删除数据吗？')) {
    try {
      await bmi.deleteBMI()
      await getList()
    } catch (e) {
      console.log(e)
    }
  }
}
</script>

